package com.villaday.idf.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import androidx.viewpager.widget.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.R;
import com.villaday.idf.base.BaseNoWhiteActivity;
import com.villaday.idf.custom.LoadDialog;
import com.villaday.idf.fragment.FodderHouseFragmentFor3;
import com.villaday.idf.fragment3.WineShopDetailsFragment;
import com.villaday.idf.model.Favor;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.model.behaviorsEntity;
import com.villaday.idf.model3.HotelDetailsEntity;
import com.villaday.idf.util.BitMapUtil;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.ImageViewUtils;
import com.villaday.idf.util.LogUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.StatusBarUtil;
import com.villaday.idf.util.ToastUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.villaday.idf.custom.ErWeiMaDialog.saveImageToSdCard;


/**
 * 酒店详情页
 */
public class WineShopDetailsActivity extends BaseNoWhiteActivity {


    @BindView(R.id.vp_fhwsd)
    ViewPager vpFhwsd;
    @BindView(R.id.toolbar_iconBack)
    ImageButton toolbarIconBack;

    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.ll_left)
    LinearLayout llLeft;
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.iv_center)
    ImageView ivCenter;
    @BindView(R.id.ll_center)
    LinearLayout llCenter;
    @BindView(R.id.toolbar_fa)
    ImageButton toolbarFa;
    @BindView(R.id.toolbar_iconNext)
    ImageButton toolbarIconNext;
    @BindView(R.id.toolbar_iconLine)
    View toolbarIconLine;
    @BindView(R.id.ll_tool)
    LinearLayout llTool;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.rl_fhswsd)
    RelativeLayout rlFhswsd;

    private LoadDialog loadDialog;
    private int scrollY = 0;
    private String hotelID;
    private HotelDetailsEntity mHotelDetailsEntity;
    private boolean favorite = false;
    private int height = 0;
    private int vpPosition = 0;
    private int mType = 0;
    private WineShopDetailsFragment mWineShopDetailsFragment;
    private boolean mHotelVip = false;
    private Bundle bundle;

    @Override
    protected int getViewResId() {
        return R.layout.activity_find_house_wine_shop_details;
    }


    @Override
    protected void init() {
        //是否是Vip
        RefreshtokenEntity.BodyBean roleInfo = SharedPreferencesUtil.getRoleInfo(this);
        if (roleInfo != null && !roleInfo.getMember().getType().equals("0")) {
            mHotelVip = true;
            llRight.setVisibility(View.VISIBLE);
        } else {
            llRight.setVisibility(View.GONE);
        }
        //初始化相关数据
        initActivity();
        getHotelDetails();
    }


    private void getHotelDetails() {
        Map<String, String> map = new HashMap<>();
        OkHttpUtil.getJSON(this, Constant.URL.hotelsDetails + hotelID, map, new OkHttpUtil.OnDataListener() {

            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                    if (!TextUtils.isEmpty(json)) {
                        mHotelDetailsEntity = new Gson().fromJson(json, HotelDetailsEntity.class);
                        if (mHotelDetailsEntity.getCode().equals(Constant.Strings.SUC)) {
                            HotelDetailsEntity.BodyBean body = mHotelDetailsEntity.getBody();
                            //是否收藏
                            favorite = body.isFavorite();
                            toolbarFa.setSelected(favorite);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.toolbar_iconBack, R.id.ll_left, R.id.ll_center, R.id.ll_right, R.id.toolbar_fa, R.id.toolbar_iconNext})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_iconBack: //返回
                onBackPressed();
                break;
            case R.id.ll_left:
                ivLeft.setVisibility(View.VISIBLE);
                ivCenter.setVisibility(View.INVISIBLE);
                ivRight.setVisibility(View.INVISIBLE);
                vpFhwsd.setCurrentItem(0);
                mWineShopDetailsFragment.setSkip(0, 0);
                break;
            case R.id.ll_center:
                ivLeft.setVisibility(View.INVISIBLE);
                ivCenter.setVisibility(View.VISIBLE);
                ivRight.setVisibility(View.INVISIBLE);
                vpFhwsd.setCurrentItem(0);
                mWineShopDetailsFragment.setSkip(1, 0);
                break;
            case R.id.ll_right:
                ivLeft.setVisibility(View.INVISIBLE);
                ivCenter.setVisibility(View.INVISIBLE);
                ivRight.setVisibility(View.VISIBLE);
                vpFhwsd.setCurrentItem(1);
                break;
            case R.id.toolbar_fa://喜欢
                showDialog();
                Map<String, Object> map = new HashMap<>();
                Favor collect = new Favor(!favorite);
                OkHttpUtil.postJson(this, String.format(Constant.URL.member_favor, "7", mHotelDetailsEntity.getBody().getId()), collect, map, new OkHttpUtil.OnDataListener() {
                    @Override
                    public void onResponse(String url, String json) {
                        dismissDialogAndRefresh();
                        LogUtil.jLog().e(json);
                        behaviorsEntity behaviorsEntity = new Gson().fromJson(json, behaviorsEntity.class);
                        if (behaviorsEntity.getBody().getStatus() == 1) {
                            favorite = !favorite;
                            toolbarFa.setSelected(favorite);
                            ScrollY();
                            ToastUtil.initToast(WineShopDetailsActivity.this, favorite ? "已喜欢" : "已取消喜欢");
                        } else {
                            ToastUtil.initToast(WineShopDetailsActivity.this, "操作失败");
                        }
                    }

                    @Override
                    public void onFailure(String url, String error) {

                    }
                });
                break;
            case R.id.toolbar_iconNext: //右边图标分享
                showDialog();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        HotelDetailsEntity.BodyBean.ShareBean shareResponse = mHotelDetailsEntity.getBody().getShare();
                        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();

                        miniProgramObj.webpageUrl = shareResponse.getLink(); // 兼容低版本的网页链接

                        Bitmap bitmap;
                        try {
                            LogUtil.jLog().e(shareResponse.getImageUrl());
                            File file = saveImageToSdCard(WineShopDetailsActivity.this, shareResponse.getImageUrl());
                            String fileName = file.getAbsolutePath();
                            bitmap = BitMapUtil.getBitmap(fileName);
                        } catch (Exception e) {

                            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img_find_bg);
                        }

                        miniProgramObj.userName = shareResponse.getMiniAppId();     // 小程序原始id
                        miniProgramObj.path = shareResponse.getPath();            //小程序页面路径
                        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
                        msg.title = shareResponse.getTitle();                 // 小程序消息title
                        msg.description = shareResponse.getDesc();


                        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 80 * 1024);// 小程序消息desc

                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = "webpage";
                        req.message = msg;
                        req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前支持会话
                        IWXAPI api = WXAPIFactory.createWXAPI(WineShopDetailsActivity.this, Constant.ID.WeChat_APP_ID, false);
                        api.sendReq(req);
                    }
                }).start();
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        dismissDialogAndRefresh();
    }

    /**
     * 初始化相关数据
     */
    private void initActivity() {
        StatusBarUtil.setTranslucentForImageViewInFragment(this, null);
        StatusBarUtil.setLightMode(this);
        //配置HotelId
        bundle = getIntent().getExtras();
        if (bundle != null) {
            hotelID = bundle.getString("hotelId", hotelID);
            //            hotelID = "V5xxpR865z";
            LogUtil.jLog().e(hotelID);
            if (null != bundle.getString("distance1")) {
                SharedPreferencesUtil.saveDistance(this, 0);
            }
        }
        height = PhoneUtil.dp2px(this, 240);
        ImageViewUtils.setImageViewColor(ivLeft, Color.argb(255, 51, 51, 51));
        //右边图标
        toolbarIconNext.setVisibility(View.VISIBLE);

        //设置ViewPager切换效果，即实现画廊效果
        vpFhwsd.setOffscreenPageLimit(3);
        vpFhwsd.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                return mHotelVip ? 2 : 1;
            }

            @Override
            public Fragment getItem(int i) {
                switch (i) {
                    case 0://详情
                        mWineShopDetailsFragment = WineShopDetailsFragment.instance(hotelID);
                        mWineShopDetailsFragment.setOnScrollWineListener(new WineShopDetailsFragment.onScrollWineListener() {
                            @Override
                            public void onScroll(int scrollxY, int height, int type) {
                                scrollY = scrollxY;
                                mType = type;
                                if (vpPosition == 0) {
                                    if (type == 0) {
                                        ivLeft.setVisibility(View.VISIBLE);
                                        ivCenter.setVisibility(View.INVISIBLE);
                                    } else if (type == 1) {
                                        ivLeft.setVisibility(View.INVISIBLE);
                                        ivCenter.setVisibility(View.VISIBLE);
                                    }
                                }
                                ScrollY();
                            }

                            @Override
                            public void onChange(int i) {
                                vpFhwsd.setCurrentItem(i);
                            }
                        });
                        return mWineShopDetailsFragment;
                    case 1://素材
                        FodderHouseFragmentFor3 fodderHouseFragmentFor3 = FodderHouseFragmentFor3.instance("9V5xNYbEyz", "9V5xNYbEyz", "380.32", false);
                        return fodderHouseFragmentFor3;
                }
                return mWineShopDetailsFragment;
            }
        });
        vpFhwsd.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
                if ((i == 0 || i == 1) && v == 0) {
                    vpPosition = i;
                }
                if (SharedPreferencesUtil.getDistance(getApplicationContext()) != -1) {
                    scrollY = SharedPreferencesUtil.getDistance(getApplicationContext());
                }
                mWineShopDetailsFragment.setSkip(2, scrollY);
                if (i == 1 && v == 0) {
                    ivLeft.setVisibility(View.INVISIBLE);
                    ivCenter.setVisibility(View.INVISIBLE);
                    ivRight.setVisibility(View.VISIBLE);
                    //设置标题的背景颜色
                    llTool.setBackgroundColor(Color.argb(255, 255, 255, 255));
                    tvLeft.setTextColor(Color.argb((int) 255, 50, 50, 50));
                    tvCenter.setTextColor(Color.argb((int) 255, 50, 50, 50));
                    tvRight.setTextColor(Color.argb((int) 255, 50, 50, 50));

                    ImageViewUtils.setImageViewColor(ivLeft, Color.argb(255, 51, 51, 51));
                    ImageViewUtils.setImageViewColor(ivCenter, Color.argb(255, 51, 51, 51));
                    ImageViewUtils.setImageViewColor(ivRight, Color.argb(255, 51, 51, 51));
                    ImageViewUtils.setImageViewColor(toolbarIconBack, Color.argb(255, 51, 51, 51));
                    ImageViewUtils.setImageViewColor(toolbarIconNext, Color.argb(255, 51, 51, 51));
                    ImageViewUtils.setImageViewColor(toolbarFa, Color.argb(255, 247, 54, 55));

                }

                if (i == 0 && v == 0) {
                    if (SharedPreferencesUtil.getDistance(getApplicationContext()) != -1) {
                        scrollY = SharedPreferencesUtil.getDistance(getApplicationContext());
                    }
                    mWineShopDetailsFragment.setSkip(2, scrollY);
                    ivRight.setVisibility(View.INVISIBLE);
                    if (mType == 0) {
                        ivLeft.setVisibility(View.VISIBLE);
                        ivCenter.setVisibility(View.INVISIBLE);
                    } else if (mType == 1) {
                        ivLeft.setVisibility(View.INVISIBLE);
                        ivCenter.setVisibility(View.VISIBLE);
                    } else {
                        ivLeft.setVisibility(View.INVISIBLE);
                        ivCenter.setVisibility(View.VISIBLE);
                    }
                    ScrollY();
                }
            }

            @Override
            public void onPageSelected(int i) {

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }


    private void ScrollY() {
        if (scrollY <= 5) {
            //设置标题的背景颜色
            llTool.setBackgroundColor(Color.argb(0, 255, 255, 255));
            tvLeft.setTextColor(Color.argb((int) 0, 50, 50, 50));
            tvCenter.setTextColor(Color.argb((int) 0, 50, 50, 50));
            tvRight.setTextColor(Color.argb((int) 0, 50, 50, 50));

            ImageViewUtils.setImageViewColor(ivLeft, Color.argb(0, 255, 255, 255));
            ImageViewUtils.setImageViewColor(ivCenter, Color.argb(0, 255, 255, 255));
            ImageViewUtils.setImageViewColor(ivRight, Color.argb(0, 255, 255, 255));
            ivLeft.setVisibility(View.INVISIBLE);
            ivCenter.setVisibility(View.INVISIBLE);
            ivRight.setVisibility(View.INVISIBLE);
            ImageViewUtils.setImageViewColor(toolbarIconBack, Color.argb(255, 255, 255, 255));
            ImageViewUtils.setImageViewColor(toolbarIconNext, Color.argb(255, 255, 255, 255));
            ImageViewUtils.setImageViewColor(toolbarFa, Color.argb(255, 255, 255, 255));
        } else if (scrollY > 5 && scrollY <= height) {

            // 滑动距离小于图的高度时，设置背景和字体颜色颜色透明度渐变
            float scale = (float) scrollY / height;
            float alpha = (255 * scale);
            llTool.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
            tvLeft.setTextColor(Color.argb((int) alpha, 50, 50, 50));
            tvCenter.setTextColor(Color.argb((int) alpha, 50, 50, 50));
            ImageViewUtils.setImageViewColor(ivLeft, Color.argb((int) alpha, 255, 255, 255));
            tvRight.setTextColor(Color.argb((int) alpha, 50, 50, 50));

            ImageViewUtils.setImageViewColor(ivLeft, ImageViewUtils.blendColors(Color.argb(255, 255, 255, 255), Color.argb(255, 51, 51, 51), scale));
            ImageViewUtils.setImageViewColor(ivCenter, ImageViewUtils.blendColors(Color.argb(255, 255, 255, 255), Color.argb(255, 51, 51, 51), scale));
            ImageViewUtils.setImageViewColor(ivRight, ImageViewUtils.blendColors(Color.argb(255, 255, 255, 255), Color.argb(255, 51, 51, 51), scale));
            ImageViewUtils.setImageViewColor(toolbarIconBack, ImageViewUtils.blendColors(Color.argb(255, 255, 255, 255), Color.argb(255, 51, 51, 51), scale));
            ImageViewUtils.setImageViewColor(toolbarIconNext, ImageViewUtils.blendColors(Color.argb(255, 255, 255, 255), Color.argb(255, 51, 51, 51), scale));

            if (favorite) {
                if (scrollY > PhoneUtil.dp2px(this, 30)) {
                    ImageViewUtils.setImageViewColor(toolbarFa, Color.argb(255, 247, 54, 55));
                } else {
                    ImageViewUtils.setImageViewColor(toolbarFa, Color.argb(255, 255, 255, 255));
                }
            } else {
                ImageViewUtils.setImageViewColor(toolbarFa, ImageViewUtils.blendColors(Color.argb(255, 255, 255, 255), Color.argb(247, 0, 0, 0), scale));
            }
        } else {
            // 滑动到图下面设置普通颜色

            llTool.setBackgroundColor(Color.argb(255, 255, 255, 255));
            tvLeft.setTextColor(Color.argb((int) 255, 50, 50, 50));
            tvCenter.setTextColor(Color.argb((int) 255, 50, 50, 50));
            tvRight.setTextColor(Color.argb((int) 255, 50, 50, 50));

            ImageViewUtils.setImageViewColor(ivLeft, Color.argb(255, 51, 51, 51));
            ImageViewUtils.setImageViewColor(ivCenter, Color.argb(255, 51, 51, 51));
            ImageViewUtils.setImageViewColor(ivRight, Color.argb(255, 51, 51, 51));
            ImageViewUtils.setImageViewColor(toolbarIconBack, Color.argb(255, 51, 51, 51));
            ImageViewUtils.setImageViewColor(toolbarIconNext, Color.argb(255, 51, 51, 51));

            if (favorite) {
                ImageViewUtils.setImageViewColor(toolbarFa, Color.argb(255, 247, 54, 55));
            } else {
                ImageViewUtils.setImageViewColor(toolbarFa, Color.argb(255, 0, 0, 0));
            }

        }
    }


    /**
     * 设置加载框
     */
    protected void showDialog() {
        if (loadDialog == null) {
            loadDialog = LoadDialog.newInstance("加载中");
        }
        loadDialog.show(this.getSupportFragmentManager(), "loading");
    }

    /**
     * 停止加载框
     */
    protected void dismissDialogAndRefresh() {
        if (loadDialog != null) {
            loadDialog.dismiss();//获取信息后关闭对话框
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (null == bundle.getString("distance1")) {
            SharedPreferencesUtil.saveDistance(this, -1);
        }

        setResult(RESULT_OK);
    }

    @Override
    public void onPause() {
        super.onPause();
        setResult(RESULT_OK);
    }

    @Override
    public void onBackPressed() {
        if (!BackHandlerHelper.handleBackPress(this)) {
            super.onBackPressed();
        }
    }
}
